# application/mapper/system/device.py
import datetime
from application.extensions.databases import db
from application.models.system.device import SysDevice
from typing import List, Dict, Any


class DeviceMapper:
    """设备数据访问层"""

    @staticmethod
    def get_device_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> tuple:
        """
        分页获取设备列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件（如 deviceName, deviceModel, manufacturer, status 等）
        :return: (设备列表, 总数)
        """
        query = db.session.query(SysDevice)

        # 添加查询条件
        if conditions:
            if conditions.get("deviceName"):
                query = query.filter(
                    SysDevice.device_name.like(f"%{conditions['deviceName']}%")
                )
            if conditions.get("deviceModel"):
                query = query.filter(
                    SysDevice.device_model.like(f"%{conditions['deviceModel']}%")
                )
            if conditions.get("manufacturer"):
                query = query.filter(
                    SysDevice.manufacturer.like(f"%{conditions['manufacturer']}%")
                )
            if conditions.get("deviceStatus"):
                query = query.filter(
                    SysDevice.device_status == conditions["deviceStatus"]
                )
            if conditions.get("communicationType"):
                query = query.filter(
                    SysDevice.communication_type == conditions["communicationType"]
                )

        # 获取总数
        total = query.count()

        # 分页查询
        offset = (page_num - 1) * page_size
        device_list = (
            query.order_by(SysDevice.device_id)
            .offset(offset)
            .limit(page_size)
            .all()
        )

        return device_list, total

    @staticmethod
    def create_device(device: SysDevice) -> SysDevice:
        """
        创建设备
        :param device: 设备对象
        :return: 创建后的设备对象
        """
        db.session.add(device)
        db.session.commit()
        return device

    @staticmethod
    def update_device(device: SysDevice) -> SysDevice:
        """
        更新设备
        :param device: 设备对象（需包含 device_id）
        :return: 更新后的设备对象
        """
        db.session.commit()
        return device

    @staticmethod
    def get_device_by_id(device_id: int) -> SysDevice:
        """
        根据ID获取设备
        :param device_id: 设备ID
        :return: 设备对象
        """
        return (
            db.session.query(SysDevice)
            .filter(SysDevice.device_id == device_id)
            .first()
        )

    @staticmethod
    def delete_device(device: SysDevice) -> None:
        """
        删除设备（软删除）
        :param device: 设备对象
        :return: None
        """
        # 假设使用 del_flag 字段进行软删除
        device.del_flag = 1  # 设置删除标志
        db.session.commit()